var roleManage = function() {

	var _init = function() {

		var table = $('#table_role');
		//  var form = $('#form1').serializeObject();
		table
				.dataTable({
					"processing" : true,
					// 开启服务器模式
					serverSide : true,
					"ajax" : {
						url : url + "s",
					},
					"autoWidth" : false,
					"columns" : [
							/*{
								"width" : "5%",
								"data" : "null",
							    "defaultContent": "<label class=\"mt-checkbox mt-checkbox-single mt-checkbox-outline\"><input type=\"checkbox\" class=\"checkboxes\" value=\"1\"><span></span></label>"
							},*/
							/*	{
									"width" : "15%",
									"data" : "id"
								},*/
							{
								"width" : "9%",
								"data" : "name"
							},
							{
								"width" : "8%",
								"data" : "phone"
							},
							{
								"width" : "6%",
								"data" : "code"
							},
							{
								"width" : "6%",
								"data" : "province"
							},
							{
								"width" : "6%",
								"data" : "city"
							},
							{
								"width" : "8%",
								"data" : "template"
							},
							{
								"width" : "8%",
								"data" : "updateOper"
							},
							{
								"width" : "9%",
								"data" : "createDate"
							},
							{
								"width" : "4%",

								"data" : "isActive",
								"render" : function(data, type, row, meta) {
									if (data == '0') {
										return "停用";
									} else if(data == '1') {
										return "正常";
									}else{
										return "已过期";
									}
								}
							},
                            {
                                "width" : "6%",
                                "data" : "stopUseDate"
                            },

							{
								"width" : "20%",
								"data" : "isActive",
								"render" : function(data, type, row, meta) {
									    var buttonStr="<button type=\"button\" class=\"btn  btn_xf_role\">续费</button>";
				                    if(agentType=='总部'){
				                    	buttonStr+="<button type=\"button\" class=\"btn  btn_change_role\">转移</button>";
				                    }
									if (data == '0') {
										return "<button type=\"button\" class=\"btn blue btn_edit_tenant\">修改</button><button type=\"button\" class=\"btn red btn_qy_role\">启用</button>"
												+ "<button type=\"button\" class=\"btn yellow btn_reset_role\">重置密码</button>"+buttonStr

									} else if(data =='1') {
										return "<button type=\"button\" class=\"btn blue btn_edit_tenant\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">禁用</button>"
												+ "<button type=\"button\" class=\"btn yellow btn_reset_role\">重置密码</button>"+buttonStr
									}else{
										return "<button type=\"button\" class=\"btn red btn_lapse_open \">过期启用</button>"+buttonStr;
									}
								}
							} ],
					"language" : {
						"lengthMenu" : "每页显示 _MENU_ 条记录",
						"emptyTable" : "暂无数据记录",
						"info" : "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
						"zeroRecords" : "没有搜索到匹配记录",
						"infoEmpty" : "",
						"infoFiltered" : "",
						"processing" : ""
					},
					"destroy" : true,
					"pageLength" : 5,
					"order" : [ [ 7, "desc" ] ],
					"columnDefs" : [
							{
								"orderable" : false,
								"targets" : [ 0, 10 ]
							},
							{
								"targets" : 1,
								"render" : function(data, type, row, meta) {
									return data;
								}
							},
							{
								"targets" : 2,
								"render" : function(data, type, row, meta) {
									return data;
								}
							},
							{
								"targets" : 3,
								"render" : function(data, type, row, meta) {
									return data;
								}
							},
							{
								"targets" : 4,
								"render" : function(data, type, row, meta) {
									return data;
								}
							},
							/*{
								"targets" : 6,//屢受關係
								"render" : function(data, type, row, meta) {
									var param = {
										"id" : row.createOper
									};
									var results = "--";
									$.ajax({
												url : '/a/biz/tenant/getOper',
												type : 'post',
												dataType : 'json',
												contentType : "application/json; charset=utf-8",
												async : false,
												data : JSON.stringify(param),
												success : function(result) {
													if (result.status == "1") {
														results = result.data.name;
													}
												},
												error : function(result) {
													results = "--";
												}
											})

									return results;
								}
							},*/
							{
								"targets" : 7,
								"render" : function(data, type, row, meta) {
									return moment(data).format(
											'YYYY-MM-DD HH:mm');
								}
							} ,{
                            "targets" : 9,
                            "render" : function(data, type, row, meta) {
                                return moment(data).format(
                                    'YYYY-MM-DD');
                            }
                        }],
					"dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
							+ "<t>" + "<'row relative'<'col-md-5'i><'col-md-7'>p>",
					"fnInitComplete" : function() {
					}
				});

		// 禁用
		table.on('click', '.btn_del_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要禁用吗？",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							// alert('提交删除');
							var _data = JSON.stringify({
								id : _id
							});
							request_role_del(_data, function(res) {
								// 正确
								table.DataTable().ajax.reload();
							}, function(err) {
								// 错误
								alert(err);
							})
						}
					}
				}
			});
		});

		table.on('click', '.btn_qy_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要启用吗？",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							// alert('提交删除');
							var _data = JSON.stringify({
								id : _id
							});
							request_role_del(_data, function(res) {
								// 正确
								table.DataTable().ajax.reload();
							}, function(err) {
								// 错误
								alert(err);
							})
						}
					}
				}
			});
		});

		table.on('click', '.btn_edit_tenant', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var cpid = oData_arr[0].id;
			//			 var cpid = $(this).parent().parent().find("td").eq(1).text();
			window.location.href = "/p/biz/tenant/show?id="
					+ encodeURIComponent(cpid);
		});

		table.on('click', '.btn_reset_role', function(event) {
			// var cpid = $(this).parent().parent().find("td").eq(1).text();
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var cpid = oData_arr[0].id;
			 bootbox.dialog({
	                message: "确定要重置密码吗？(默认重置为123456)",
	                title: "提示",
	                buttons: {
	                    cancel: {
	                        label: "取消",
	                        className: "btn dark btn-outline"
	                    },
	                    success: {
	                        label: "确定",
	                        className: "btn green",
	                        callback: function() {
	                        	
								$.ajax({
									 url: '/a/biz/tenant/resetPwd',
									 type: 'put',
									 dataType: 'json',
									 contentType:"application/json; charset=utf-8",
									 data: JSON.stringify({
											id : cpid
										}),
									 })
									 .done(function(data) {
										 if (data.status === '1') {
											 alert("重置密码成功！");
											 table.DataTable().ajax.reload();
										 } else if (data.status === '2') {
                                          //	错误
											 alert(data.message);
										//mdTool.showMessage(data.message);
											}
										 
										
									 });
	                        }
	                    }
	                }
	            });
			
		});
		
		
		table.on('click', '.btn_lapse_open', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var cpid = oData_arr[0].id;
			 bootbox.dialog({
	                message: "确定要开启商户使用权限",
	                title: "提示",
	                buttons: {
	                    cancel: {
	                        label: "取消",
	                        className: "btn dark btn-outline"
	                    },
	                    success: {
	                        label: "确定",
	                        className: "btn green",
	                        callback: function() {
								$.ajax({
									 url: '/a/biz/tenant/openTenant',
									 type: 'POST',
									 dataType: 'json',
									 contentType:"application/json; charset=utf-8",
									 data: JSON.stringify({
											id : cpid
										}),
									 })
									 .done(function(data) {
										 if (data.status === '1') {
											 table.DataTable().ajax.reload();
										 } else if (data.status === '2') {
                                          //	错误
										mdTool.showMessage(data.message);
											}
									 });
	                        }
	                    }
	                }
	            });
		});


        table.on('click', '.btn_xf_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var cpid = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要续费一年吗",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                            $.ajax({
                                url: '/a/biz/tenant/xf',
                                type: 'POST',
                                dataType: 'json',
                                contentType:"application/json; charset=utf-8",
                                data: JSON.stringify({
                                    id : cpid
                                }),
                            })
                                .done(function(data) {
                                    if (data.status === '1') {
                                        table.DataTable().ajax.reload();
                                    } else if (data.status === '2') {
                                        //	错误
                                        alert(data.message);
                                    }
                                });
                        }
                    }
                }
            });
        });
		
        //代理商转移
        table.on('click', '.btn_change_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            var parentId=oData_arr[0].parentId;
            var agentId=oData_arr[0].agentId;
            showAgentList(_id,agentId);
            $('.change-link').modal('show');
            selectId=_id;
         
        });
		 $('#search').click(function(event){
			 var form = $('#form1').serializeObject();
			 var param =  {
					"name" : form.name,
					"phone" : form.phone,
					"createDate1":form.createDate1,
					"createDate2":form.createDate2,
					"templateId":form.templateId,
					"province":form.province,
					"city":form.city
				}
			 $('#table_role').DataTable().search(JSON.stringify(param)  ).draw();
//		          table.DataTable().ajax.reload();
		      });

		$("#update").on("click", function() {
			var _data = $("#modal_new_role").serializeObject();
			if (!mdTool.validate(_data.phone, 'require')) {
				mdTool.showMessage('请输入手机号码');
				return;
			}
			if (!mdTool.validate(_data.phone, 'phone')) {
				mdTool.showMessage('手机号码格式不正确，请重新输入');
				return;
			}
			/*if (!mdTool.validate(_data.templateId, 'require')) {
				mdTool.showMessage('请选择模板');
				return;
			}*/
			if (!mdTool.validate(_data.name, 'require')) {
				mdTool.showMessage('请输入商户名称');
				return;
			}
			if (!mdTool.validate(_data.address, 'require')) {
				mdTool.showMessage('请输入地址');
				return;
			}
			var param={"tenant":{"id":_data.id,"phone":_data.phone,"loginName":_data.loginName,"password":_data.password,"name":_data.name,"templateId":_data.templateId,
                "province":_data.province,"city":_data.city,"address":_data.address},"operator":{"phone":_data.phone}}
		
			$.ajax({
				url : '/a/biz/tenant/tenant',
				type : 'POST',
				dataType : 'json',
				contentType:"application/json; charset=utf-8",
				data : JSON.stringify(param),
			}).done(function(data) {
				if (data.status === '1') {
					// 正确
					window.location.href="/p/biz/tenant";
		        	//window.location.href="/p/biz/tenant";
				} else if (data.status === '2') {
//					错误
					mdTool.showMessage(data.message);
//					$('#modal_new_role .help-block').html(data.message); // 返回错误信息
				}
			});
		//	$("#modal_new_role").submit();
		})

	}
	return {
		init : function() {
			_init();
		}

	};

}();
var roleForm = function() {
	// 新建表单验证
	return {
		init : function() {
		}

	};
}();

$(function() {
	roleManage.init();
	roleForm.init();
});

function add() {
	window.location.href = "/p/biz/tenant/totenant";
}

function beback() {
	window.location.href = "/p/biz/tenant";
}


var storage = window.localStorage;  
var localAgent = JSON.parse(storage["agent"]);   
var agentType="";
if(localAgent){
	agentType=localAgent.type;
}

var selectId="";


function showAgentList(id,agentId){
    var table = $('#table_agent_change');

    var table=table.dataTable({
        "processing": true,
        // 开启服务器模式
        serverSide: true,
        "ajax": {
        	url:"/a/biz/agentList",
        	data:{"id":agentId}
        },
        "autoWidth": true,
        "destroy":true,
        "columns": [{
                "data": "name"
            },
            {
                "data": "levelId",
                "render": function(data, type, row, meta) {
                	var val=data;
                	if(data!=null&&data!=''){
        				$.ajax({
        					url : '/a/biz/alevel/obj',
        					type : 'post',
        					dataType : 'json',
        					contentType:"application/json; charset=utf-8",
        					async: false,
        					data : JSON.stringify({ id: data }),
        				}).done(function(r) {
        					if (r.status === '1') {
        						val=r.data.name;

        					} else if (r.status === '2') {
        					}
        				});
        				return val;
                	}else
                		return "";	
                }
            },
            {
                "data": "type"
            },
            {
                "data": "phone"
            },
            {
                "data": "province"
            },
            {


                "data": "city"
            },
           {
                "data": "null",
                "render":function(data, type, row, meta) {
                	return row.totalCount-row.leftCount
                }
            }, {
                "data": "leftCount"
            },
       
            {
                "data": "createDate",
                "render": function(data, type, row, meta) {
                    return moment(data).format('YYYY-MM-DD');
                }
            },
            {
                "data": "null",
                "defaultContent": "<button type=\"button\" class=\"btn btn_select_role pull-right\">选取</button>"
            }
        ],
        "language": {
        	url: '/assets/pages/Chinese.json'
        },
        "pageLength": 5,
        "order": [
            [8, "desc"]
        ],
        "columnDefs": [{
            "orderable": false,
            "targets": [0, 9]
        } ],
        "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
            "<t>" +
            "<'row'<'col-md-5'i><'col-md-7'>p>",
        "fnInitComplete": function() {},
        "fnDrawCallback": function(){
      
      	}
    });
    
    
  
}

//选择代理商
$('#table_agent_change').on('click', '.btn_select_role', function(event) {
 	var oData_arr = $('#table_agent_change').DataTable().rows($(this).parents("tr")).data(); // 操作行对象
 	var _id=oData_arr[0].id;
// 	bootbox.distory();
 	  bootbox.dialog({
           message: "确定要转移吗？",
           title: "提示",
           buttons: {
               cancel: {
                   label: "取消",
                   className: "btn dark btn-outline"
               },
               success: {
                   label: "确定",
                   className: "btn green",
                   callback: function() {
                   	
               		$.ajax({
               			url : '/a/biz/updateZyTennat',
               			type : 'POST',
               			dataType : 'json',
               			contentType:"application/json; charset=utf-8",
               			data : JSON.stringify({ id: selectId ,agentId:_id}),
               		}).done(function(data) {
               			if (data.status === '1') {
               				// 正确
               				 $('.change-link').modal('hide');
               				 $('#table_role').DataTable().ajax.reload();
               			} else if (data.status === '2') {
//               				  //	错误
               			}
               		});
               		
                   }
               }
           }
       });
 	});



